#include "operationstation.h"
#include "ui_operationstation.h"
#include "bubblesort.h"
#include "insertsort.h"
#include "mergesort.h"
#include "selectsort.h"
#include "quicksort.h"
#include "heapsort.h"
#include "shellsort.h"

Operationstation::Operationstation(VisualData *pVisualData,
                                   QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::Operationstation),
    _visual_data(pVisualData)
{
    ui->setupUi(this);
    setupConnection();
    setupAlgo();
}

Operationstation::~Operationstation()
{
    delete ui;
}

void Operationstation::setupAlgo()
{
    addAlgo(new BubbleSort(this));
    addAlgo(new InsertSort(this));
    addAlgo(new MergeSort(this));
    addAlgo(new SelectSort(this));
    addAlgo(new QuickSort(this));
    addAlgo(new HeapSort(this));
    addAlgo(new ShellSort(this));
}

void Operationstation::addAlgo(IAlgo *algo)
{
    ui->comboBox_algo->addItem(algo->name());
    ui->comboBox_algo->setCurrentText(algo->name());
    _algos[algo->name()] = algo;
    algo->setData(_visual_data);
}

void Operationstation::setupConnection()
{
    connect(ui->pushButton_init, &QPushButton::clicked, this, [&](){
        _visual_data->Init(ui->lineEdit_num_count->text().toInt());
        IAlgo *pAlgo = _algos[ui->comboBox_algo->currentText()];
        pAlgo->setInterval(ui->lineEdit_interval->text().toInt());
    });

    connect(ui->pushButton_sort, &QPushButton::clicked, this, [&](){
        IAlgo *pAlgo = _algos[ui->comboBox_algo->currentText()];
        pAlgo->run();
        ui->lineEdit_run_count->setText(QString::number(pAlgo->runTime()));
    });

    connect(ui->pushButton_reverse, &QPushButton::clicked, this, [&](){
        QVector<int> rdata;
        QVector<int> &data = _visual_data->GetData();
        rdata.reserve(data.size());
        for(int i = data.size() - 1; i >= 0; --i){
            rdata.append(data[i]);
        }
        data = rdata;
        _visual_data->Refresh();
    });
}
